﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 邮件收发
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.11.28 
    /// </summary>
    internal class EmailService : DataFactory, EmailIService
    {
        /// <summary>
        /// 列表（收件箱）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<EmailReceiveEntity>> GetReceiveList(string userId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<EmailReceiveEntity>().And(m => m.CreatorUserId == userId);
                var queryParam = input.queryJson.ToObject();
                //日期范围（近7天、近1月、近3月、自定义）
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.Date >= startTime && t.Date <= endTime);
                }
                //关键字（发件人、主题）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Sender.Contains(input.keyword) || m.Subject.Contains(input.keyword));
                }
                return await db.GetIQueryable<EmailReceiveEntity>().Where(queryWhere).OrderByDescending(t => t.Date).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 列表（未读邮件）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<EmailReceiveEntity>> GetUnreadList(string userId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<EmailReceiveEntity>().And(m => m.CreatorUserId == userId && m.Read == 0);
                var queryParam = input.queryJson.ToObject();
                //日期范围（近7天、近1月、近3月、自定义）
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.Date >= startTime && t.Date <= endTime);
                }
                //关键字（发件人、主题）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Sender.Contains(input.keyword) || m.Subject.Contains(input.keyword));
                }
                return await db.GetIQueryable<EmailReceiveEntity>().Where(queryWhere).OrderByDescending(t => t.Date).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 列表（星标件）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<EmailReceiveEntity>> GetStarredList(string userId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<EmailReceiveEntity>().And(m => m.CreatorUserId == userId && m.Starred == 1);
                var queryParam = input.queryJson.ToObject();
                //日期范围（近7天、近1月、近3月、自定义）
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.Date >= startTime && t.Date <= endTime);
                }
                //关键字（发件人、主题）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Sender.Contains(input.keyword) || m.Subject.Contains(input.keyword));
                }
                return await db.GetIQueryable<EmailReceiveEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 列表（草稿箱）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<EmailSendEntity>> GetDraftList(string userId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<EmailSendEntity>().And(m => m.CreatorUserId == userId && m.State == -1);
                var queryParam = input.queryJson.ToObject();
                //日期范围（近7天、近1月、近3月、自定义）
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.CreatorTime >= startTime && t.CreatorTime <= endTime);
                }
                //关键字（发件人、主题）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Sender.Contains(input.keyword) || m.Subject.Contains(input.keyword));
                }
                return await db.GetIQueryable<EmailSendEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);

            }
        }
        /// <summary>
        /// 列表（已发送）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<EmailSendEntity>> GetSentList(string userId, PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<EmailSendEntity>().And(m => m.CreatorUserId == userId && m.State != -1);
                var queryParam = input.queryJson.ToObject();
                //日期范围（近7天、近1月、近3月、自定义）
                if (!queryParam["startTime"].IsEmpty() && !queryParam["endTime"].IsEmpty())
                {
                    var startTime = CommonHelper.GetDateTime(queryParam["startTime"].ToString());
                    var endTime = CommonHelper.GetDateTime(queryParam["endTime"].ToString());
                    startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0, 0);
                    endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, 999);
                    queryWhere = queryWhere.And(t => t.CreatorTime >= startTime && t.CreatorTime <= endTime);
                }
                //关键字（发件人、主题）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Sender.Contains(input.keyword) || m.Subject.Contains(input.keyword));
                }
                return await db.GetIQueryable<EmailSendEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 信息（配置）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<EmailConfigEntity> GetConfigInfo(string userId)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<EmailConfigEntity>(m => m.CreatorUserId == userId);
            }
        }
        /// <summary>
        /// 信息（收件/发件）
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<object> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                var entity = new object();
                var receiveInfo = await db.GetEntityAsync<EmailReceiveEntity>(m => m.Id == id);
                if (receiveInfo != null)
                {
                    receiveInfo.BodyText = WebHelper.HtmlDecode(receiveInfo.BodyText);
                    entity = receiveInfo;
                }
                else
                {
                    var sendInfo = await db.GetEntityAsync<EmailSendEntity>(m => m.Id == id);
                    sendInfo.BodyText = WebHelper.HtmlDecode(sendInfo.BodyText);
                    entity = sendInfo;
                }
                return entity;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(object entity)
        {
            using (var db = this.Basic)
            {
                if (entity is EmailReceiveEntity)
                    return await db.DeleteAsync((EmailReceiveEntity)entity);
                else
                    return await db.DeleteAsync((EmailSendEntity)entity);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(object entity)
        {
            using (var db = this.Basic)
            {
                if (entity is List<EmailReceiveEntity>)
                    return await db.InsertAsync((List<EmailReceiveEntity>)entity);
                else
                    return await db.InsertAsync((EmailSendEntity)entity);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(object entity)
        {
            using (var db = this.Basic)
            {
                if (entity is EmailReceiveEntity)
                    return await db.UpdateAsync((EmailReceiveEntity)entity);
                else
                    return await db.UpdateAsync((EmailSendEntity)entity);
            }
        }
        /// <summary>
        /// 保存邮件配置
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> SaveConfig(EmailConfigEntity entity)
        {
            using (var db = this.Basic)
            {
                var data = await this.GetConfigInfo(entity.CreatorUserId);
                if (data == null)
                {
                    entity.Id = CommonHelper.Guid;
                    entity.CreatorTime = DateTime.Now;
                    entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                    return await db.InsertAsync(entity);
                }
                else if (UserProvider.Instance.Get().UserId != null)
                {
                    entity.Id = data.Id;
                    return await db.UpdateAsync(entity);
                }
                else
                {
                    throw new Exception("保存失败，请重新登陆");
                }
            }
        }
        /// <summary>
        /// 获取已收邮件数
        /// </summary>
        /// <param name="mAccount">邮箱账户</param>
        /// <returns></returns>
        public async Task<int> GetReceiveCount(string mAccount)
        {
            using (var db = this.Basic)
            {
                var startTime = (DateTime.Now.ToString("yyyy-MM-dd") + " 00:00").ToDate();
                var endTime = (DateTime.Now.ToString("yyyy-MM-dd") + " 23:59").ToDate();
                return await db.GetCountAsync<EmailReceiveEntity>(m => m.MAccount == mAccount && m.CreatorTime >= startTime && m.CreatorTime <= endTime);
            }
        }
    }
}
